package ServerOperation;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import Entity.InfoSystem;
import Entity.Message;
import Entity.Worker;

public class DBInfoSystem implements IDBHandler {
	
	private Connection conn;
	
	public DBInfoSystem(Connection conn) {
		super();
		this.conn = conn;
	}

	
	@Override
	public Message decipherMessage(Message msg)
	{
		// TODO Auto-generated method stub
		Message AnswerMessage = null;
		System.out.println("Server : decipherMessage ");
		int op = (msg.getOpCode()%1000);
		switch (op){
		case 1:
			AnswerMessage =  setNewInfoSystem(msg);
			break;
		case 2:
			
			break;
		case 3:
			
			break;
		case 4:
			AnswerMessage =  getAllInfoSystems(msg);
			break;
		case 5:
			
			break;
		case 6:
			break;
		case 7:
			break;
		
		}
		return AnswerMessage;

    }

	private Message getAllInfoSystems(Message msg) 
	{
		Message AnswerMessage = null;
				
		String SpecficQuery = new String("SELECT * "+
										"FROM info_system");
		System.out.println(SpecficQuery);
		try 
		{
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(SpecficQuery);
			
			System.out.println(rs.toString());
			
			List<InfoSystem> InfoSystemList = new ArrayList<InfoSystem>();
			while(rs.next())
			{  
				int id = rs.getInt("id");
				String name = rs.getString("name") ;    
				String description = rs.getString("description") ; 
				
				InfoSystemList.add(new InfoSystem(id ,name, description, null) );
			}
			System.out.println(" we heave " + InfoSystemList.size());
			AnswerMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(), InfoSystemList);
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		return AnswerMessage;
		
	}


	private Message setNewInfoSystem(Message msg) 
	{
		Message AnswerMessage = null;
			
		InfoSystem info = (InfoSystem) msg.getDataGram();
		String infoName = info.getName();
		String Description =info.getDescription();
		String Supervisor = info.getSupervisor().getId() + "";
		
		String SpecficQuery = new String("INSERT INTO info_system (name, description, supervisor) " +
				                         "VALUES (' " + infoName + "', '" + Description + "', '" + Supervisor + "');");
		System.out.println(SpecficQuery);
		try 
		{
			Statement stmt = conn.createStatement();
			stmt.executeUpdate(SpecficQuery);
			System.out.println("Server - setNewInfoSystem : Add new info ");
			AnswerMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(), true);
		}
		catch (SQLException e) 
		{
			AnswerMessage = new Message(msg.getOpCode()+1000, msg.getMessageID(), false);
			e.printStackTrace();
		}
		return AnswerMessage;
	}
}
